

package com.yungu.swift.order.thread.inform;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author Zerrion
 * @version 1.0
 * @description 线程池操作处理类
 * @date 2017/10/26 18:12
 */
public class InformThreadPoolUtil {
    /**
     * 线程池操作处理
     */
    static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pool-task-%d").build();
    static ExecutorService POOL = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1,
            200, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024),
            threadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 执行线程
     *
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        POOL.execute(runnable);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        // 禁止提交新任务
        POOL.shutdown();
        try {
            // 等待现有任务终止
            if (!POOL.awaitTermination(60, TimeUnit.SECONDS)) {
                // 取消当前正在执行的任务
                POOL.shutdownNow();
                // 等待一段时间让任务响应被取消
                if (!POOL.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("Pool did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            // 如果当前线程也中断，则取消
            POOL.shutdownNow();
            // 保留中断状态
            Thread.currentThread().interrupt();
        }
    }

    public static ExecutorService getPool(){
        return POOL;
    }
}
